package org.jash.learnmvp.news;

import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import org.jash.learnmvp.R;
import org.jash.learnmvp.entity.CategoryEntity;
import org.jash.learnmvp.entity.NewsEntity;
import org.jash.learnmvp.mvp.BaseFragment;

import java.util.List;
import java.util.stream.Collectors;

public class NewsFragment extends BaseFragment<ConStruct.INewsView, NewsPresenter> implements ConStruct.INewsView {

    private Banner banner;
    private TabLayout tab;
    private ViewPager2 pager;
    private CategoryAdapter adapter;
    @Override
    protected int layoutId() {
        return R.layout.activity_news;
    }

    @Override
    protected void initData() {
        presenter = new NewsPresenter();
        presenter.loadTopHot();
        presenter.loadNewsCategory();
    }

    @Override
    protected void initView() {
        adapter = new CategoryAdapter(this);
        banner = getView().findViewById(R.id.banner);
        pager = getView().findViewById(R.id.pager);
        tab = getView().findViewById(R.id.tab);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(imageView)
                        .load(path)
                        .into(imageView);
            }
        }).setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        pager.setAdapter(adapter);
        new TabLayoutMediator(tab, pager, (t, position) -> t.setText(adapter.getTitle(position))).attach();
    }

    @Override
    public void success(List<NewsEntity.DataBean> list) {
        banner.update(list.stream().map(NewsEntity.DataBean::getImgurl).collect(Collectors.toList()),
                list.stream().map(NewsEntity.DataBean::getTitle).collect(Collectors.toList()));
    }

    @Override
    public void categorySuccess(List<CategoryEntity.DataBean> list) {
        adapter.addAll(list);
    }

    @Override
    public void failure(Throwable t) {
        Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e("TAG", "failure: ", t);

    }
}